// 顶部：仅类型导入 + 拆分 logger 的值/类型导入
import Logger from "../../logger";
import type { ILogger } from "../../logger";
import { LoggerLevel } from "../../logger";
import utilsIs from "../is";
import type { IUtilsReplace } from "./replace";

export type {
    IUtilsReplace,
}

class UtilsReplace implements IUtilsReplace {
    private logger: ILogger;

    constructor(loggerLevel?: LoggerLevel) {
        this.logger = new Logger('utils_replace', loggerLevel);
    }

    strByJson(data: string, json: object): string {
        const isJson = utilsIs.json(json);
        if (!isJson) {
            this.logger.warn('replaceStrByJson()', `参数不是json格式`)
            return '';
        }
        let _value = data;
        for (const item in json) {
            if (!json.hasOwnProperty(item)) continue;
            const name = `{${item}}`;
            if (_value.indexOf(name) >= 0) {
                do {
                    _value = _value.replace(name, (json as Record<string, string>)[item]);
                } while (_value.indexOf(name) >= 0)
            }
        }
        return _value;
    }

    spliceToUrlByJson(url: string, json: object): string {
        const isJson = utilsIs.json(json);
        if (!isJson) {
            this.logger.warn('replaceStrByJson()', `参数不是json格式`)
            return '';
        }
        let _value = `${url}${url.indexOf('?') > 0 ? utilsIs.lastStr(url, '&') ? '' : '&' : '?'}`;
        for (const item in json) {
            if (!json.hasOwnProperty(item)) continue;
            const name = `{${item}}`;
            if (_value.indexOf(name) >= 0) {
                do {
                    _value = _value.replace(name, (json as Record<string, string>)[item]);
                } while (_value.indexOf(name) >= 0)
            } else {
                _value = `${_value}${item}=${(json as Record<string, string>)[item]}&`
            }
        }
        if (utilsIs.lastStr(_value, ['?', '&'])) _value = _value.substring(0, _value.length - 1);
        return _value;
    }

}

export default new UtilsReplace() as IUtilsReplace;
